<template>
  <!-- 上传头像 -->
  <el-upload class="avatar-uploader"
    :action="action" :show-file-list="showList" :auto-upload="autoUpload"
    :headers="headers" :multiple="multiple" :data="data" :name="name"
    :with-credentials="cookie" :drag="drag" :accept="accept"
      :file-list="fileList" :list-type="listType" :limit="limit"
    :on-success="onSuccess" :on-error="onError" :before-upload="beforeUpload">
    <slot>
      <slot name="img" v-if="imageUrl">
        <img :src="imageUrl" class="avatar">
      </slot>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </slot>
  </el-upload>
</template>
<script>
export default {
  name: 'cAvatar',
  props: {
    action: String,
    headers: Object,
    multiple: Boolean,
    data: Object,
    name: String,
    cookie: Boolean,
    showList: Boolean,
    drag: Boolean,
    autoUpload: {
      type: Boolean,
      default: true
    },
    accept: String,
    fileList: Array,
    listType: String,
    limit: Number,
    imageUrl: String,
    before: Function,
    onSuccess: Function,
    onError: Function
  },
  data() {
    return {

    }
  },
  created() {
  },
  methods: {
    beforeUpload(file) {
      if (this.before) {
        const res = this.before()
        if (res != null) {
          return res
        }
      }
      const isJPG = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$msg('上传头像只支持 图片 格式!', 'error')
      }
      if (!isLt2M) {
        this.$msg('上传头像图片大小不能超过 2MB!', 'error')
      }
      return isJPG && isLt2M
    }
  },
  filters: {

  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader{
  ::v-deep .el-upload{
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409EFF;
    }
  }
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
